package com.littlerpc.protocol.net.common;


import com.littlerpc.protocol.exception.RpcException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author ChengPeng
 * @date 2017/6/14
 */
public class RpcFuturePool {

    private static Map<String, RpcFuture<RpcResponse>> futures = new ConcurrentHashMap<>(1000);

    /**
     * 获取future
     */
    public static RpcFuture<RpcResponse> getFuture(String requestId) {
        if (!futures.containsKey(requestId)) {
            return null;
        }
        return futures.get(requestId);
    }

    /**
     * 创建future
     */
    public static RpcFuture<RpcResponse> createFuture(String requestId) {
        if (futures.containsKey(futures)) {
            throw new RpcException(requestId + " 已经存在");
        }

        RpcFuture<RpcResponse> f = new RpcFuture<>();
        futures.put(requestId,f);

        return f;
    }


    /**
     * 删除future
     */
    public static void removeFuture(String requestId) {
        futures.remove(requestId);
    }

    /**
     * 保存future
     * @param requestId
     * @param future
     */
    public static void saveFuture(String requestId, RpcFuture<RpcResponse> future) {
        futures.put(requestId, future);
    }

}
